package org.example.dao;

import com.mysql.cj.util.StringUtils;
import org.example.model.ClassInfo;
import org.example.model.PageBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ClassDao {
    public ResultSet getClassList(Connection con, PageBean pagebean, ClassInfo calfo) throws SQLException {
        ResultSet rs = null;
        StringBuffer sb = new StringBuffer("select * from t_class");
        if (calfo != null && !StringUtils.isNullOrEmpty(calfo.getClassName())) {
            sb.append(" and className like '%" + calfo.getClassName() + "%'");
        }

        if (pagebean != null) {
            sb.append(" limit " + pagebean.getStart() + "," + pagebean.getRows());
        }

        PreparedStatement pstmt = con.prepareStatement(sb.toString().replaceFirst("and", "where"));
        return pstmt.executeQuery();
    }

    public int count(Connection con, ClassInfo calfo) throws SQLException {
        StringBuffer sb = new StringBuffer("select count(*) as total from t_class");
        if(calfo != null) {
            if (StringUtils.isNullOrEmpty(calfo.getClassName())) {
                sb.append(" and className like '%" + calfo.getClassName() + "%'");
            }
        }

        PreparedStatement pstmt = con.prepareStatement(sb.toString().replaceFirst("and", "where"));
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getInt("total");
        } else {
            return 0;
        }
    }

    public int insertClass(Connection conn, ClassInfo classInfo) throws SQLException {
        String sql="INSERT INTO t_class value(null,?,?) ";
        PreparedStatement pstmt=conn.prepareStatement(sql);
        pstmt.setString(1, classInfo.getClassDesc());
        pstmt.setString(2, classInfo.getClassName());
        return pstmt.executeUpdate();
    }

    public int updateClass(Connection conn, ClassInfo classInfo) throws SQLException {
        String sql="UPDATE t_class set className=?,classDesc=? where id=?";
        PreparedStatement pstmt=conn.prepareStatement(sql);
        pstmt.setString(1,classInfo.getClassName());
        pstmt.setString(2, classInfo.getClassDesc());
        pstmt.setInt(3, classInfo.getId());
        return pstmt.executeUpdate();
    }

    //批量删除
    public int deleteClass(Connection con, String ids) throws SQLException {
        String sql="delete from t_class where id in ("+ids+")";
        PreparedStatement pstmt=con.prepareStatement(sql);
        return pstmt.executeUpdate();
    }
}
